import { useState, useEffect } from 'react';
import { submissionAPI } from '../services/api';

function History() {
  const [submissions, setSubmissions] = useState([]);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState(null);
  const [selectedSubmission, setSelectedSubmission] = useState(null);

  useEffect(() => {
    loadSubmissions();
  }, []);

  const loadSubmissions = async () => {
    try {
      setLoading(true);
      setError(null);
      const response = await submissionAPI.getSubmissions({
        page: 1,
        limit: 50,
        sortBy: 'createdAt',
        sortOrder: 'desc',
      });
      console.log('API响应:', response);
      console.log('提交记录:', response.data.submissions);
      setSubmissions(response.data.submissions);
    } catch (err) {
      // 游客模式，简化错误处理
      setError('加载历史记录失败，请稍后重试');
      console.error('加载历史记录错误:', err);
    } finally {
      setLoading(false);
    }
  };

  const handleViewDetail = async (submissionId) => {
    try {
      const response = await submissionAPI.getSubmission(submissionId);
      setSelectedSubmission(response.data);
    } catch (err) {
      alert('加载详情失败');
      console.error('加载详情错误:', err);
    }
  };

  const handleBack = () => {
    setSelectedSubmission(null);
  };

  const formatDate = (dateString) => {
    const date = new Date(dateString);
    return date.toLocaleString('zh-CN', {
      year: 'numeric',
      month: '2-digit',
      day: '2-digit',
      hour: '2-digit',
      minute: '2-digit',
    });
  };

  if (loading) {
    return (
      <div className="flex justify-center items-center min-h-screen bg-gradient-to-br from-slate-50 via-blue-50 to-indigo-50">
        <div className="text-center">
          <div className="inline-block animate-spin rounded-full h-16 w-16 border-t-4 border-b-4 border-blue-600 mb-4"></div>
          <p className="text-xl text-gray-600 font-medium">加载历史记录中...</p>
        </div>
      </div>
    );
  }

  if (error) {
    return (
      <div className="min-h-screen bg-gradient-to-br from-slate-50 via-blue-50 to-indigo-50 py-8">
        <div className="max-w-4xl mx-auto px-4">
          <div className="bg-gradient-to-r from-red-50 to-pink-50 border-l-4 border-red-500 text-red-700 px-6 py-4 rounded-r-xl shadow-lg flex items-center mb-6">
            <span className="text-2xl mr-3">⚠️</span>
            <span className="font-semibold">{error}</span>
          </div>
          <div className="text-center">
            <button
              onClick={() => (window.location.href = '/')}
              className="px-8 py-3 bg-gradient-to-r from-blue-600 to-indigo-600 text-white rounded-xl hover:from-blue-700 hover:to-indigo-700 font-semibold shadow-lg hover:shadow-xl transform hover:-translate-y-0.5 transition-all"
            >
              🏠 返回首页
            </button>
          </div>
        </div>
      </div>
    );
  }

  if (selectedSubmission) {
    // 详情页面
    return (
      <div className="min-h-screen bg-gradient-to-br from-slate-50 via-blue-50 to-indigo-50 py-8">
        <div className="max-w-6xl mx-auto px-4">
          {/* 返回按钮 */}
          <button
            onClick={handleBack}
            className="mb-6 flex items-center text-blue-600 hover:text-blue-700 font-semibold bg-white px-4 py-2 rounded-lg shadow-md hover:shadow-lg transition-all"
          >
            <span className="mr-2">←</span>
            返回列表
          </button>

          {/* 页面标题 */}
          <div className="text-center mb-8">
            <h1 className="text-4xl font-extrabold bg-gradient-to-r from-blue-600 via-indigo-600 to-purple-600 bg-clip-text text-transparent mb-2">
              📝 提交详情
            </h1>
            <p className="text-gray-600">Submission Details</p>
          </div>

          <div className="grid grid-cols-1 lg:grid-cols-3 gap-6">
            {/* 左侧：题目信息 */}
            <div className="lg:col-span-1">
              <div className="bg-white rounded-2xl shadow-2xl border-2 border-blue-100 overflow-hidden sticky top-6">
                {/* 题目标题栏 */}
                <div className="bg-gradient-to-r from-blue-600 to-indigo-600 text-white px-6 py-4">
                  <div className="flex items-center">
                    <span className="text-3xl mr-3">📄</span>
                    <div>
                      <h3 className="text-sm font-medium opacity-90">考试题目</h3>
                      <h2 className="text-xl font-bold">{selectedSubmission.exerciseId?.title || '题目已删除'}</h2>
                    </div>
                  </div>
                </div>

                {/* 题目内容 */}
                <div className="p-6">
                  {selectedSubmission.exerciseId && (
                    <>
                      {/* 标签 */}
                      <div className="flex gap-2 mb-4">
                        <span className="px-3 py-1.5 bg-gradient-to-r from-blue-100 to-blue-200 text-blue-800 rounded-lg text-xs font-bold uppercase">
                          {selectedSubmission.exerciseId.type}
                        </span>
                        <span className={`px-3 py-1.5 rounded-lg text-xs font-bold uppercase ${
                          selectedSubmission.exerciseId.difficulty === 'easy' ? 'bg-gradient-to-r from-green-100 to-green-200 text-green-800' :
                          selectedSubmission.exerciseId.difficulty === 'medium' ? 'bg-gradient-to-r from-yellow-100 to-yellow-200 text-yellow-800' :
                          'bg-gradient-to-r from-red-100 to-red-200 text-red-800'
                        }`}>
                          {selectedSubmission.exerciseId.difficulty}
                        </span>
                      </div>

                      {/* 题目正文 */}
                      <div className="bg-gradient-to-br from-blue-50 via-indigo-50 to-purple-50 rounded-xl p-5 mb-5 border-2 border-blue-100">
                        <p className="text-gray-800 leading-relaxed text-base font-medium">
                          {selectedSubmission.exerciseId.content}
                        </p>
                      </div>
                    </>
                  )}

                  {/* 提交信息 */}
                  <div className="space-y-3">
                    <div className="bg-white border-2 border-purple-200 rounded-xl p-4">
                      <div className="flex items-center">
                        <div className="bg-purple-100 p-2 rounded-lg mr-3">
                          <span className="text-2xl">📅</span>
                        </div>
                        <div>
                          <p className="text-xs text-gray-500 font-medium">提交时间</p>
                          <p className="text-sm font-bold text-gray-800">{formatDate(selectedSubmission.createdAt)}</p>
                        </div>
                      </div>
                    </div>
                    <div className="bg-white border-2 border-green-200 rounded-xl p-4">
                      <div className="flex items-center">
                        <div className="bg-green-100 p-2 rounded-lg mr-3">
                          <span className="text-2xl">📝</span>
                        </div>
                        <div>
                          <p className="text-xs text-gray-500 font-medium">字数统计</p>
                          <p className="text-lg font-bold text-gray-800">{selectedSubmission.wordCount} words</p>
                        </div>
                      </div>
                    </div>
                  </div>
                </div>
              </div>
            </div>

            {/* 右侧：作文和评分 */}
            <div className="lg:col-span-2 space-y-6">
              {/* 您的作文 */}
              <div className="bg-white rounded-2xl shadow-2xl border-2 border-indigo-100 overflow-hidden">
                <div className="bg-gradient-to-r from-indigo-600 to-purple-600 text-white px-6 py-4">
                  <div className="flex items-center">
                    <span className="text-3xl mr-3">✍️</span>
                    <div>
                      <h3 className="text-sm font-medium opacity-90">您的作文</h3>
                      <h2 className="text-xl font-bold">Your Answer</h2>
                    </div>
                  </div>
                </div>
                <div className="p-6">
                  <div className="bg-gradient-to-br from-white to-blue-50/30 border-2 border-indigo-200 rounded-xl p-6 shadow-inner">
                    <p className="text-gray-800 whitespace-pre-wrap leading-relaxed text-lg">
                      {selectedSubmission.content}
                    </p>
                  </div>
                </div>
              </div>

              {/* 评分结果 */}
              {selectedSubmission.scores && (
                <div className="bg-white rounded-2xl shadow-2xl border-2 border-green-100 overflow-hidden">
                  <div className="bg-gradient-to-r from-green-600 to-emerald-600 text-white px-6 py-4">
                    <div className="flex items-center justify-between">
                      <div className="flex items-center">
                        <span className="text-3xl mr-3">🎯</span>
                        <div>
                          <h3 className="text-sm font-medium opacity-90">AI评分结果</h3>
                          <h2 className="text-xl font-bold">Scoring Results</h2>
                        </div>
                      </div>
                      <div className="bg-white text-green-700 px-6 py-3 rounded-full">
                        <div className="text-center">
                          <p className="text-xs font-medium opacity-75">总分</p>
                          <p className="text-4xl font-extrabold">{selectedSubmission.scores.overall}</p>
                        </div>
                      </div>
                    </div>
                  </div>

                  <div className="p-6">
                    {/* 四个维度评分 */}
                    <div className="grid grid-cols-2 gap-4 mb-6">
                      <div className="bg-gradient-to-br from-blue-50 to-blue-100 rounded-xl p-5 border-2 border-blue-200">
                        <div className="flex items-center justify-between">
                          <div>
                            <p className="text-xs text-blue-600 font-semibold mb-1">任务完成</p>
                            <p className="text-sm text-gray-600">Task Achievement</p>
                          </div>
                          <div className="text-4xl font-extrabold text-blue-700">
                            {selectedSubmission.scores.taskAchievement}
                          </div>
                        </div>
                      </div>

                      <div className="bg-gradient-to-br from-green-50 to-green-100 rounded-xl p-5 border-2 border-green-200">
                        <div className="flex items-center justify-between">
                          <div>
                            <p className="text-xs text-green-600 font-semibold mb-1">连贯性</p>
                            <p className="text-sm text-gray-600">Coherence</p>
                          </div>
                          <div className="text-4xl font-extrabold text-green-700">
                            {selectedSubmission.scores.coherence}
                          </div>
                        </div>
                      </div>

                      <div className="bg-gradient-to-br from-purple-50 to-purple-100 rounded-xl p-5 border-2 border-purple-200">
                        <div className="flex items-center justify-between">
                          <div>
                            <p className="text-xs text-purple-600 font-semibold mb-1">词汇</p>
                            <p className="text-sm text-gray-600">Vocabulary</p>
                          </div>
                          <div className="text-4xl font-extrabold text-purple-700">
                            {selectedSubmission.scores.vocabulary}
                          </div>
                        </div>
                      </div>

                      <div className="bg-gradient-to-br from-orange-50 to-orange-100 rounded-xl p-5 border-2 border-orange-200">
                        <div className="flex items-center justify-between">
                          <div>
                            <p className="text-xs text-orange-600 font-semibold mb-1">语法</p>
                            <p className="text-sm text-gray-600">Grammar</p>
                          </div>
                          <div className="text-4xl font-extrabold text-orange-700">
                            {selectedSubmission.scores.grammar}
                          </div>
                        </div>
                      </div>
                    </div>

                    {/* AI反馈 */}
                    {selectedSubmission.feedback && (
                      <div className="bg-gradient-to-r from-yellow-50 to-amber-50 border-l-4 border-yellow-400 rounded-r-xl p-5">
                        <div className="flex">
                          <span className="text-3xl mr-3">💡</span>
                          <div className="flex-1">
                            <h4 className="font-bold text-yellow-800 mb-2 text-lg">AI 反馈建议</h4>
                            <p className="text-gray-700 leading-relaxed">
                              {selectedSubmission.feedback}
                            </p>
                          </div>
                        </div>
                      </div>
                    )}
                  </div>
                </div>
              )}
            </div>
          </div>
        </div>
      </div>
    );
  }

  // 列表页面
  return (
    <div className="min-h-screen bg-gradient-to-br from-slate-50 via-blue-50 to-indigo-50 py-8">
      <div className="max-w-7xl mx-auto px-4">
        {/* 页面标题 */}
        <div className="text-center mb-10">
          <div className="inline-flex items-center justify-center mb-4">
            <div className="bg-gradient-to-r from-blue-600 to-indigo-600 text-white p-4 rounded-2xl shadow-lg">
              <span className="text-5xl">📚</span>
            </div>
          </div>
          <h1 className="text-5xl font-extrabold bg-gradient-to-r from-blue-600 via-indigo-600 to-purple-600 bg-clip-text text-transparent mb-3">
            提交历史记录
          </h1>
          <p className="text-xl text-gray-600 font-medium">Submission History</p>
          <div className="mt-4 inline-block bg-white px-6 py-2 rounded-full shadow-md border-2 border-blue-100">
            <span className="text-sm text-gray-600">📊 查看您的写作进步轨迹</span>
          </div>
        </div>

        {submissions.length === 0 ? (
          <div className="bg-white rounded-2xl shadow-xl p-12 text-center border-2 border-gray-100">
            <div className="text-gray-300 text-8xl mb-6">📝</div>
            <h3 className="text-2xl font-bold text-gray-700 mb-4">还没有提交记录</h3>
            <p className="text-gray-500 mb-6">开始您的第一次雅思写作练习吧！</p>
            <button
              onClick={() => (window.location.href = '/')}
              className="px-8 py-3 bg-gradient-to-r from-blue-600 to-indigo-600 text-white rounded-xl hover:from-blue-700 hover:to-indigo-700 font-semibold shadow-lg hover:shadow-xl transform hover:-translate-y-0.5 transition-all"
            >
              🚀 开始练习
            </button>
          </div>
        ) : (
          <div className="grid gap-6">
            {submissions.map((submission, index) => (
              <div
                key={submission._id}
                className="bg-white rounded-2xl shadow-lg hover:shadow-2xl transition-all cursor-pointer border-2 border-gray-100 hover:border-blue-200 overflow-hidden transform hover:-translate-y-1"
                onClick={() => handleViewDetail(submission._id)}
              >
                <div className="flex">
                  {/* 左侧：序号和状态 */}
                  <div className="bg-gradient-to-br from-blue-600 to-indigo-600 text-white p-6 flex flex-col items-center justify-center min-w-[100px]">
                    <div className="text-sm font-medium opacity-75 mb-1">NO.</div>
                    <div className="text-4xl font-extrabold">{submissions.length - index}</div>
                  </div>

                  {/* 中间：题目信息 */}
                  <div className="flex-1 p-6">
                    <div className="flex items-start justify-between mb-3">
                      <div className="flex-1">
                        <h3 className="text-xl font-bold text-gray-800 mb-2 flex items-center">
                          <span className="mr-2">📄</span>
                          {submission.exerciseId?.title || '题目已删除'}
                        </h3>
                        <div className="flex gap-2 mb-3">
                          {submission.exerciseId?.type && (
                            <span className="px-3 py-1 bg-blue-100 text-blue-800 rounded-lg text-xs font-bold">
                              {submission.exerciseId.type}
                            </span>
                          )}
                          {submission.exerciseId?.difficulty && (
                            <span className={`px-3 py-1 rounded-lg text-xs font-bold ${
                              submission.exerciseId.difficulty === 'easy' ? 'bg-green-100 text-green-800' :
                              submission.exerciseId.difficulty === 'medium' ? 'bg-yellow-100 text-yellow-800' :
                              'bg-red-100 text-red-800'
                            }`}>
                              {submission.exerciseId.difficulty}
                            </span>
                          )}
                        </div>
                        <div className="flex gap-6 text-sm text-gray-600">
                          <span className="flex items-center">
                            <span className="mr-1">📅</span>
                            {formatDate(submission.createdAt)}
                          </span>
                          <span className="flex items-center">
                            <span className="mr-1">📝</span>
                            {submission.wordCount} words
                          </span>
                        </div>
                      </div>

                      {/* 右侧：分数 */}
                      {submission.scores?.overall ? (
                        <div className="ml-6 text-center bg-gradient-to-br from-green-50 to-emerald-50 rounded-2xl p-6 border-2 border-green-200 min-w-[120px]">
                          <div className="text-5xl font-extrabold text-green-600 mb-1">
                            {submission.scores.overall}
                          </div>
                          <div className="text-xs text-gray-600 font-medium">总分</div>
                          <div className="mt-3 grid grid-cols-2 gap-2 text-xs">
                            <div className="bg-white rounded-lg p-1">
                              <div className="text-blue-600 font-bold">{submission.scores.taskAchievement}</div>
                              <div className="text-gray-500 text-[10px]">任务</div>
                            </div>
                            <div className="bg-white rounded-lg p-1">
                              <div className="text-green-600 font-bold">{submission.scores.coherence}</div>
                              <div className="text-gray-500 text-[10px]">连贯</div>
                            </div>
                            <div className="bg-white rounded-lg p-1">
                              <div className="text-purple-600 font-bold">{submission.scores.vocabulary}</div>
                              <div className="text-gray-500 text-[10px]">词汇</div>
                            </div>
                            <div className="bg-white rounded-lg p-1">
                              <div className="text-orange-600 font-bold">{submission.scores.grammar}</div>
                              <div className="text-gray-500 text-[10px]">语法</div>
                            </div>
                          </div>
                        </div>
                      ) : (
                        <div className="ml-6">
                          <span className="px-4 py-2 bg-yellow-100 text-yellow-800 rounded-full text-sm font-semibold">
                            {submission.status === 'pending' ? '⏳ 评分中' : '❌ 失败'}
                          </span>
                        </div>
                      )}
                    </div>
                  </div>
                </div>

                {/* 底部：查看详情提示 */}
                <div className="bg-gradient-to-r from-blue-50 to-indigo-50 px-6 py-3 border-t border-gray-100">
                  <div className="flex items-center justify-between text-sm">
                    <span className="text-gray-600">点击查看完整内容和评分详情</span>
                    <span className="text-blue-600 text-lg">→</span>
                  </div>
                </div>
              </div>
            ))}
          </div>
        )}
      </div>
    </div>
  );
}

export default History;